package com.zwz.mall.base;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.zwz.mall.R;
import com.zwz.mall.utils.TUtil;
import com.zwz.mall.utils.ToastUtils;

import java.text.SimpleDateFormat;
import java.util.HashSet;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.pedant.SweetAlert.SweetAlertDialog;
import io.reactivex.disposables.Disposable;


/**
 * des:基类fragment
 * Created by wushenghui on 2017/4/23.
 */

public abstract class BaseFragment<T extends BasePresenter, E extends BaseModel> extends Fragment
{
    protected View rootView;
    public T mPresenter;
    public E mModel;
    private Unbinder bind;
    private SweetAlertDialog mLoadingDialog;

    protected boolean isVisible;
    private boolean isPrepared;
    private boolean isFirst = true;
    private HashSet<Disposable> mSubcribers;
    public SimpleDateFormat simpleDateFormat;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(getLayoutResource(), container, false);
        }
        //         缓存的rootView需要判断是否已经被加过parent，
//         如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }

        bind = ButterKnife.bind(this, rootView);
        mPresenter = TUtil.getT(this, 0);
        mModel = TUtil.getT(this, 1);
        if (mPresenter != null) {
            mPresenter.mContext = this.getActivity();
        }
        // HH:mm:ss
        simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        initView();

        initPresenter();
//            fillData();
        bindEven();
        return rootView;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
//        Log.d("TAG", "fragment->setUserVisibleHint");
        if (getUserVisibleHint()) {
            isVisible = true;
            lazyLoad();
        } else {
            isVisible = false;
//            onInvisible();
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
//        Log.d("TAG", "fragment->onCreate");
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
//        Log.d("TAG", "fragment->onActivityCreated");
        isPrepared = true;
        lazyLoad();
    }

    protected void lazyLoad() {
        if (!isPrepared || !isVisible || !isFirst) {
            return;
        }
        Log.d("TAG", getClass().getName() + "->initData()");
        fillData();
        isFirst = false;
    }

    //获取布局文件
    protected abstract int getLayoutResource();

    //简单页面无需mvp就不用管此方法即可,完美兼容各种实际场景的变通
    public abstract void initPresenter();

    //初始化view
    protected abstract void initView();

    //获取数据
    protected abstract void fillData();

    //绑定事件
    protected abstract void bindEven();

    @Override
    public void onResume() {
        super.onResume();
    }

    /**
     * 通过Class跳转界面
     **/
    public void startActivity(Class<?> cls) {
        startActivity(cls, null);
    }

    /**
     * 通过Class跳转界面
     **/
    public void startActivityForResult(Class<?> cls, int requestCode) {
        startActivityForResult(cls, null, requestCode);
    }

    /**
     * 含有Bundle通过Class跳转界面
     **/
    public void startActivityForResult(Class<?> cls, Bundle bundle,
                                       int requestCode) {
        Intent intent = new Intent();
        intent.setClass(getActivity(), cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }

    /**
     * 含有Bundle通过Class跳转界面
     **/
    public void startActivity(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(getActivity(), cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }
    @Override
    public void onPause() {
        ToastUtils.cancel ();
        super.onPause ();
    }
    /**
     * 设置状态栏高度
     *
     * @param statusBarHeight
     */
    public void setStatusBarHeight(View view, ViewGroup.LayoutParams layoutParams, int statusBarHeight) {
        layoutParams.height = statusBarHeight;
        view.setLayoutParams(layoutParams);
    }

    /**
     * 获取状态栏高度
     *
     * @return
     */
    public int getStatusBarHeight() {
        //获取status_bar_height资源的ID
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            return getResources().getDimensionPixelSize(resourceId);
        }
        /*
        // todo
        // dp互转px工具
        //默认为20dp
         */

        return 0;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unregisterSubscribers();
        bind.unbind();

        if (mPresenter != null) {
            mPresenter.onDestroy();
        }
    }

    //加载方式
    public void showLoadingDialog(String msg) {
        if (mLoadingDialog == null) {
            mLoadingDialog = new SweetAlertDialog(getActivity(), SweetAlertDialog.PROGRESS_TYPE);
            mLoadingDialog.getProgressHelper().setBarColor(getResources().getColor(R.color.red_btn_bg_color));
            mLoadingDialog.setCancelable(false);
            mLoadingDialog.setTitleText(msg);
        }
        mLoadingDialog.show();
    }

    public void dismissLoadingDialog() {
        if (mLoadingDialog != null) {
            mLoadingDialog.dismiss();
        }
    }

    /**
     * 注册Rx订阅
     *
     * @param subscriber
     */
    protected void registerSubscriber(Disposable subscriber) {
        if (subscriber == null) {
            return;
        }

        if (mSubcribers == null) {
            mSubcribers = new HashSet<>();
        }

        mSubcribers.add(subscriber);
    }

    /**
     * 取消Rx订阅
     */
    protected void unregisterSubscribers() {
        if (mSubcribers == null) {
            return;
        }

        for (Disposable subscriber : mSubcribers) {
            if (subscriber != null) {
                subscriber.dispose();
            }
        }
        mSubcribers.clear();
        mSubcribers = null;
    }

    /**
     * 短暂显示Toast提示(来自String)
     **/
    public void showShortToast(String text) {
        ToastUtils.showShort(text);
    }

    /**
     * 短暂显示Toast提示(id)
     **/
    public void showShortToast(int resId) {
        ToastUtils.showShort(resId);
    }

}
